package com.wugh.fast.generator;

import org.apache.commons.lang3.StringUtils;
import org.mybatis.generator.api.GeneratedJavaFile;
import org.mybatis.generator.api.IntrospectedTable;
import tk.mybatis.mapper.generator.TemplateFilePlugin;
import tk.mybatis.mapper.generator.model.TableClass;
import tk.mybatis.mapper.generator.model.TableColumnBuilder;

import java.lang.reflect.Field;
import java.util.List;
import java.util.Properties;

/**
 * 说明:
 *
 * @author wugh
 * @date 2019-01-25 15:52
 */
public class FastTemplateFilePlugins extends TemplateFilePlugin {
    /**
     * 文件扩展名
     */
    private String extension;
    /**
     * 文件忽略后缀
     */
    private String ignoreSuffix;
    private String mapperSuffix;

    private String fileName;

    private Field templateFilePluginFileNameField;

    public Field getTemplateFilePluginFileNameField() {
        if (templateFilePluginFileNameField == null) {
            try {
                templateFilePluginFileNameField = TemplateFilePlugin.class.getDeclaredField("fileName");
                templateFilePluginFileNameField.setAccessible(true);
            } catch (NoSuchFieldException e) {
                throw new RuntimeException(e);
            }
        }
        return templateFilePluginFileNameField;
    }

    @Override
    public List<GeneratedJavaFile> contextGenerateAdditionalJavaFiles(IntrospectedTable introspectedTable) {
        if (StringUtils.isBlank(fileName)) {
            //如果设置文件名字,通过类名和extension,强放射设置TemplateFilePlugin.fileName
            TableClass tableClass = TableColumnBuilder.build(introspectedTable);
            String fileName = tableClass.getShortClassName();
            if (StringUtils.isNotBlank(ignoreSuffix) && fileName.endsWith(ignoreSuffix)) {
                fileName = StringUtils.substringBeforeLast(fileName, ignoreSuffix);
            }
            fileName += mapperSuffix + "." + extension;
            try {
                getTemplateFilePluginFileNameField().set(this, fileName);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        }
        return super.contextGenerateAdditionalJavaFiles(introspectedTable);
    }

    @Override
    public void setProperties(Properties properties) {
        this.extension = properties.getProperty("extension");
        this.ignoreSuffix = properties.getProperty("ignoreSuffix", "");
        properties.setProperty("ignoreSuffix", ignoreSuffix);
        this.mapperSuffix = properties.getProperty("mapperSuffix");
        this.fileName = properties.getProperty("fileName");
        if (StringUtils.isBlank(fileName) && StringUtils.isNotBlank(extension)) {
            properties.setProperty("fileName", "all." + extension);
        }
        super.setProperties(properties);

    }
}
